# -*- coding:utf-8 -*-
import pymysql
from datetime import datetime
class Database:
    def __init__(self,db,table):
        self.db = db
        self.table = table


    def connection(self):
        config = {'host': '5.180.76.28',
                  'port': 35311,
                  'user': 'root',
                  'passwd': '1234',
                  'charset': 'utf8',
                  'database':self.db,
                  'local_infile': 1
                  }
        connection = pymysql.connect(**config)

        #链接database
        #创建可执行sql语句的游标
        cursor = connection.cursor()
        #查询
        sql = 'select * from {};'.format(self.table)
        #执行
        count = cursor.execute(sql)

        #获取MySQL中的数据字段名称
        self.fields = cursor.description
        self.cursor,self.connection = cursor,connection;


    def close(f):
        def test(self,*args,**kwargs):
            try:
                f(self,*args,**kwargs)
                #关闭连接
                self.connection.close()
                #关闭游标
                self.cursor.close()
                print("成功关闭连接和游标.")
            except:
                print("程序某函数已关闭连接!")
        return test

    def guan(self):
        self.connection.close()
        self.cursor.close()
        print("成功关闭连接和游标")

 

    @close
    def inserts(self,*val):
        
        '''
        多条数据插入
        '''

        sql = "insert into static_motion (description,times,submission_date) value (%s,%s,%s)"

        self.cursor.executemany(sql,*val)
        self.connection.commit()
        print("成功插入数据")
        print(self.cursor.rowcount)

    
    def view_table(self):
        print(datetime.now())
        result = self.cursor.fetchall()
        items = dict()
        info = dict()
        for i in result:
            items[i[2]] = i[1]
            info[i[0]] = i[1]
        return items,info

    
    def update_data(self,val):
        sql='update static_motion set times=%s where id=%s;'
        result = self.cursor.execute(sql,val)
        self.connection.commit()
        if result==0:
            print("成功更新数据!")
            return result
        else:
            print("更新失败,回调函数。")
            self.call_back(val,self.update_data)
    
    def call_back(self,val,func):
        return func(val)


if __name__=="__main__":
    database = Database(db = "exercise",table = "static_motion")
    database.connection()
    database.view_table()